package com.mall.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.dao.CartMapper;
import com.mall.dao.UserMapper;
import com.mall.entity.Cart;
import com.mall.entity.User;
import com.mall.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

//定时任务
@Service
@Slf4j
public class ScheduledService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private UserMapper userMapper;

    /***
     * 每日23:59:59将redis中购物车数据写入数据库中
     */
    @Scheduled(cron = "59 59 23 * * ?")
//    @Scheduled(cron = "* * * * * ?")
    public void saveRedisToMysql(){
        //打印日志信息
        log.info("redis写入mysql定时任务开始-----"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //查询所有用户
        List<User> userList = userMapper.selectList(null);
        //根据用户id查询所有redis中的hash集合
        for (User user : userList) {
            String key = "user:"+user.getId()+":cart";
            //获取hash集合
            Map<String, String> map = RedisUtil.getMapFromHash(stringRedisTemplate, key);
            if(map != null && map.size() != 0){//购物车中有东西
                Set<Map.Entry<String, String>> entries = map.entrySet();//遍历map，写入数据库
                for (Map.Entry<String, String> entry : entries) {
                    Cart cart = JSON.parseObject(entry.getValue(), Cart.class);//将json字符串转为对象
                    log.info("-----------------------------"+cart);
                    //首先从数据库中查询这个记录如果没有才插入，如果有就修改数量即可
                    QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_id",cart.getUserId());
                    queryWrapper.eq("product_sku_id",cart.getProductSkuId());
                    queryWrapper.eq("deleted",0);//查询的是未删除的购物车
                    Cart c = cartMapper.selectOne(queryWrapper);

                    int rows = -1;
                    if(c == null){//如果没有这条记录，就新增
                        rows = cartMapper.insert(cart);
                    }else{//有就更新
                        c.setProductNum(cart.getProductNum());
                        rows = cartMapper.updateById(c);
                    }
                    if(rows == 1){
                        log.info(key+"集合中的"+cart.getProductSkuId()+"商品成功写入数据库");
                    }else{
                        log.info(key+"集合中的"+cart.getProductSkuId()+"商品写入数据库失败");
                    }
                }
            }
        }
        //打印日志信息
        log.info("redis写入mysql定时任务结束-----"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
